package com.dx.mes.service.brm.service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.hibernate.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.dx.common.table.ppt.Bis_bom;
import com.dx.common.table.ppt.Bis_bomId;
import com.dx.common.table.ppt.Bis_data;
import com.dx.common.table.ppt.Bis_mdl_def;
import com.dx.common.table.ppt.Bis_mtrl;
import com.dx.mes.common.dao.IBisBomDao;
import com.dx.mes.common.dao.IBisDataDao;
import com.dx.mes.common.dao.IBisMdlDefDao;
import com.dx.mes.common.dao.IBisMtrlDao;
import com.dx.mes.common.transcoder.util.AppContext;
import com.dx.mes.common.transcoder.util.GUIDGenerator;
import com.dx.mes.common.transcoder.util.JacksonUtil;
import com.dx.mes.common.transcoder.util.LogUtils;
import com.dx.mes.common.transcoder.util.Util;
import com.dx.mes.facade.brm.service.IFbpbisbomService;
import com.dx.mes.facade.brm.tx.Fbpbisbom.FbpbisbomI;
import com.dx.mes.facade.brm.tx.Fbpbisbom.FbpbisbomIA;
import com.dx.mes.facade.brm.tx.Fbpbisbom.FbpbisbomO;
import com.dx.mes.facade.brm.tx.Fbpbisbom.FbpbisbomOA;

import static com.dx.mes.common.bean.def.GenericDef.*;


@Service("fbpbisbomService")
@SuppressWarnings({"unchecked"})
public class FbpbisbomService implements IFbpbisbomService{

	private static final String TX_NAME = T_FBPBISBOM;
	private LogUtils logUtils;
	
	@Autowired
	private IBisBomDao bisBomDao;

	@Autowired
	private IBisMtrlDao bisMtrlDao;

	@Autowired
	private IBisMdlDefDao bisMdlDefDao;

	@Autowired
	private IBisDataDao bisDataDao;

	public String subMainProc(String evt_no,String strInMsg) {
		AppContext.clear();
		AppContext.setCurrServiceName(FbpbisbomService.class.getSimpleName());
		AppContext.setCurrEventNumber(evt_no);
		logUtils = new LogUtils(FbpbisbomService.class);
		logUtils.info("[InTrx:" + strInMsg + "]");
		String strOutTrx="";
		FbpbisbomI inTrx = new FbpbisbomI();
		FbpbisbomO outTrx = new FbpbisbomO();
		outTrx.setTrx_id(TX_NAME);
		outTrx.setType_id(TRX_OUT);	
		outTrx.setRtn_code(String.valueOf(RETURN_CODE_SET_ERROR));
		
		try {
			inTrx = JacksonUtil.fromJson(strInMsg, FbpbisbomI.class);
			char action_flg = inTrx.getAction_flg().charAt(0);
			switch (action_flg) {
			case ACTION_FLG_QUERY:
				queryByConditionFnc(inTrx,outTrx);
				break;
			case ACTION_FLG_ADD:
				addFnc(inTrx,outTrx);
				break;
			case ACTION_FLG_UPDATE:
				updateFnc(inTrx,outTrx);
				break;
			case ACTION_FLG_DELETE:
				deleteFnc(inTrx,outTrx);
				break;
			case ACTION_FLG_INQUIRE:
				queryByMtrl(inTrx,outTrx);
				break;
//			case ACTION_FLG_QUERYITEM:
//					queryByMtrloRiD(inTrx,outTrx);
//					break;
			default:
				errActionFnc(outTrx);
			}
			if (RETURN_CODE_OK.equals(outTrx.getRtn_code())) {
				bisBomDao.flushCurSession();
			} else {
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			}
		} catch (Exception ex) {
			outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
			outTrx.setRtn_mesg(ex.toString());
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		} finally {
			strOutTrx = JacksonUtil.toJSONStr(outTrx);
			logUtils.info("[OutTrx:" + strOutTrx + "]");
		}
		return strOutTrx;
	}


	public void addFnc(FbpbisbomI inTrx,FbpbisbomO outTrx) {
		FbpbisbomIA iary = inTrx.getIary().get(0);
		Bis_bomId id = new Bis_bomId();

		String mtrl_prod_id_fk = iary.getMtrl_prod_id_fk();
		String mdl_id_fk = iary.getMdl_id_fk();
		Timestamp current_timestamp = Util.getCurrentTimestamp();
		id.setMdl_id_fk(mdl_id_fk);
		id.setMtrl_prod_id_fk(mtrl_prod_id_fk);
		id.setMdl_mtrl_seq_id(GUIDGenerator.javaGUID());

		Bis_bom queryBisQrs = bisBomDao.get(id);
		if (queryBisQrs != null) {
			outTrx.setRtn_code(E_FBPBISBOM_BOM_ALREADY_EXIST + "");
			outTrx.setRtn_mesg("Record already Exist");
			return; 
		}
		Bis_mdl_def bis_mdl_def = bisMdlDefDao.get(mdl_id_fk);
		if (bis_mdl_def == null) {
			outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
			outTrx.setRtn_mesg("找不到成品型号:" + mdl_id_fk);
			return;
		}
		Bis_mtrl bis_mtrl = bisMtrlDao.get(mtrl_prod_id_fk);
		if (bis_mtrl == null) {
			outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
			outTrx.setRtn_mesg("找不到料号:" + mtrl_prod_id_fk);
			return;
		}
		Bis_bom bis_bom = new Bis_bom();
		bis_bom.setId(id);
		bis_bom.setMtrl_cate(iary.getMtrl_cate());
		bis_bom.setOpe_id_fk(iary.getOpe_id_fk());
		bis_bom.setMtrl_unit_fk(iary.getMtrl_unit_fk());
		bis_bom.setCns_flg(iary.getCns_flg());
		bis_bom.setMnt_flg(iary.getMnt_flg());
		bis_bom.setMtrl_use_qty(iary.getMtrl_use_qty());
		bis_bom.setEvt_usr(inTrx.getEvt_usr());
		bis_bom.setEvt_timestamp(current_timestamp);
		bisBomDao.save(bis_bom);

		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
		return;
	}

	public void updateFnc(FbpbisbomI inTrx,FbpbisbomO outTrx) {
		FbpbisbomIA iary = inTrx.getIary().get(0);
		String mtrl_prod_id_fk = iary.getMtrl_prod_id_fk();
		String mdl_id_fk = iary.getMdl_id_fk();
		Bis_bomId id = new Bis_bomId();
		id.setMdl_id_fk(iary.getMdl_id_fk());
		id.setMtrl_prod_id_fk(iary.getMtrl_prod_id_fk());
		id.setMdl_mtrl_seq_id(iary.getMdl_mtrl_seq_id());
		Bis_bom bis_bom = bisBomDao.get(id);
		Timestamp current_timestamp = Util.getCurrentTimestamp();
		
		Bis_mtrl bis_mtrl = bisMtrlDao.get(mtrl_prod_id_fk);
		if (bis_mtrl == null) {
			outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
			outTrx.setRtn_mesg("找不到料号:" + mtrl_prod_id_fk);
			return;
		}
		Bis_mdl_def bis_mdl_def = bisMdlDefDao.get(mdl_id_fk);
		if (bis_mdl_def == null) {
			outTrx.setRtn_code(RETURN_CODE_UNKNOWN);
			outTrx.setRtn_mesg("找不到成品型号:" + mdl_id_fk);
			return;
		}
		
		if (bis_bom == null) {
			outTrx.setRtn_code(E_READ_NOT_FOUND + "");
			outTrx.setRtn_mesg("not Found Record[BIS_BOM]");
			return ;
		}
		if (iary.getMtrl_cate()!= null) {
			bis_bom.setMtrl_cate(iary.getMtrl_cate());;
		}
		if (iary.getOpe_id_fk() != null) {
			bis_bom.setOpe_id_fk(iary.getOpe_id_fk());
		}
		if (iary.getMtrl_unit_fk() != null) {
			bis_bom.setMtrl_unit_fk(iary.getMtrl_unit_fk());
		}
		if (iary.getCns_flg() != null) {
			bis_bom.setCns_flg(iary.getCns_flg());
		}
		if (iary.getMnt_flg() != null) {
			bis_bom.setMnt_flg(iary.getMnt_flg());
		}
		if (iary.getMtrl_use_qty() != null) {
			bis_bom.setMtrl_use_qty(iary.getMtrl_use_qty());
		}
		bisBomDao.save(bis_bom);
		bis_bom.setEvt_usr(inTrx.getEvt_usr());
		bis_bom.setEvt_timestamp(current_timestamp);
//		bisMdlDefDao.update(bis_mdl_def);

		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}

	public void deleteFnc(FbpbisbomI inTrx,FbpbisbomO outTrx) {
		FbpbisbomIA iary = inTrx.getIary().get(0);
		Bis_bomId id = new Bis_bomId();
		id.setMdl_id_fk(iary.getMdl_id_fk());
		id.setMtrl_prod_id_fk(iary.getMtrl_prod_id_fk());
		id.setMdl_mtrl_seq_id(iary.getMdl_mtrl_seq_id());
		Bis_bom bis_bom = bisBomDao.get(id);
		if (bis_bom == null) {
			outTrx.setRtn_code(E_READ_NOT_FOUND + "");
			outTrx.setRtn_mesg("not Found Record[BIS_BOM]");
			return;
		}
		bisBomDao.delete(bis_bom);
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}

	public String comObj2String(Object obj) {
		if (obj != null) {
			return obj.toString();
		}
		return null;
	}

	public void queryByConditionFnc(FbpbisbomI inTrx,FbpbisbomO outTrx) {
		/***
		 * 暂只支持 by mdl_id_fk 查询
		 **/
		
		List<FbpbisbomOA> oaryList = new ArrayList<FbpbisbomOA>();

		FbpbisbomIA iary = inTrx.getIary().get(0);
		String mdlId = iary.getMdl_id_fk();
		
		String hql = "FROM Bis_bom where mdl_id_fk = ?";
		List<Bis_bom> bisBomList = bisBomDao.list(hql, mdlId);
		for (Bis_bom bisBom : bisBomList) {
			String mtrlProdId = bisBom.getId().getMtrl_prod_id_fk();
			Bis_mtrl bisMtrl = bisMtrlDao.get(mtrlProdId);
			if(bisMtrl == null){
				outTrx.setRtn_mesg("该物料["+mtrlProdId+"]不存在，请确认");
				outTrx.setRtn_code(E_BIS_MTRL + E_READ_NOT_FOUND +"");
				return; 
			}
			FbpbisbomOA oary = new FbpbisbomOA();
			oary.setMdl_id_fk(mdlId);
			oary.setMtrl_prod_id_fk(bisBom.getId().getMtrl_prod_id_fk());
			oary.setMtrl_cate(bisBom.getMtrl_cate());
			oary.setOpe_id_fk(bisBom.getOpe_id_fk());
			oary.setMtrl_use_qty(bisBom.getMtrl_use_qty());
			oary.setCns_flg(bisBom.getCns_flg());
			oary.setMnt_flg(bisBom.getMnt_flg());
			oary.setMtrl_prod_dsc(bisMtrl.getMtrl_prod_dsc());
			oary.setMtrl_unit_fk(bisBom.getMtrl_unit_fk());
			oary.setMdl_mtrl_seq_id(bisBom.getId().getMdl_mtrl_seq_id());
//			hql = "FROM Bis_data where data_cate = ? and ext_1 = ?";
//			String mtrl_mkr = "";
//			List<Bis_data> bisDataList = bisDataDao.list(hql, "CSMT", mtrlProdId);
//			for (Bis_data bisData : bisDataList) {
//				mtrl_mkr += bisData.getData_item();
//				mtrl_mkr += (bisDataList.indexOf(bisData) == bisDataList.size() - 1) ? "" : ",";
//			}
//			oary.setMtrl_mkr(mtrl_mkr);
			oaryList.add(oary);
		}

		outTrx.setOary(oaryList);
		outTrx.setTbl_cnt(oaryList.size());
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}

	public void queryByMtrl(FbpbisbomI inTrx,FbpbisbomO outTrx) {
		List<FbpbisbomOA> oaryList = new ArrayList<FbpbisbomOA>();
		FbpbisbomIA iary = inTrx.getIary().get(0);
		String hql = "FROM Bis_bom where 1=1 ";
		String mdl_id_fk = iary.getMdl_id_fk();
		String mtrl_prod_id_fk = iary.getMtrl_prod_id_fk();
		String mdl_mtrl_seq_id  = iary.getMdl_mtrl_seq_id();
		String mtrl_cate  = iary.getMtrl_cate();
		if (mdl_id_fk != null) {
			hql = hql + " and  id.mdl_id_fk='" + mdl_id_fk + "'";
		}
		if (mtrl_prod_id_fk != null) {
			hql = hql + " and  id.mtrl_prod_id_fk='" + mtrl_prod_id_fk + "'";
		}
		if (mdl_mtrl_seq_id != null) {
			hql = hql + " and  id.mdl_mtrl_seq_id='" + mdl_mtrl_seq_id + "'";
		}
		if (mtrl_cate != null) {
			hql = hql + " and  mtrl_cate='" + mtrl_cate + "'";
		}
		List<Bis_bom> bisBomList = bisBomDao.find(hql);
		for (Bis_bom bis_bom : bisBomList) {
			FbpbisbomOA oary = new FbpbisbomOA();
			oary.setMdl_id_fk(bis_bom.getId().getMdl_id_fk());
			oary.setMtrl_prod_id_fk(bis_bom.getId().getMtrl_prod_id_fk());
			oary.setMdl_mtrl_seq_id(bis_bom.getId().getMdl_mtrl_seq_id());
			oary.setMtrl_cate(bis_bom.getMtrl_cate());
			oary.setOpe_id_fk(bis_bom.getOpe_id_fk());
			oary.setMtrl_use_qty(bis_bom.getMtrl_use_qty());
			oary.setMtrl_unit_fk(bis_bom.getMtrl_unit_fk());
			oary.setMnt_flg(bis_bom.getMnt_flg());
			oary.setCns_flg(bis_bom.getCns_flg());
			oaryList.add(oary);
		}
		outTrx.setOary(oaryList);
		outTrx.setTbl_cnt(oaryList.size());
		outTrx.setRtn_code(RETURN_CODE_OK);
		outTrx.setRtn_mesg(RETURN_MESG_OK);
	}
//	private void queryByMtrloRiD(FbpbisbomI inTrx, FbpbisbomO outTrx) {
//		List<FbpbisbomOA> oaryList = new ArrayList<FbpbisbomOA>();
//		FbpbisbomIA iary = inTrx.getIary().get(0);
//		String hql = "FROM Bis_bom where 1=1 ";
//		String mtrl_cate  = iary.getMtrl_cate();
//		String mdl_id_fk = iary.getMdl_id_fk();
//		if (mdl_id_fk != null){
//			hql = hql + " and  id.mdl_id_fk='" + mdl_id_fk + "'";
//		}
//		if (mtrl_cate != null) {
//			hql = hql + " and  mtrl_cate='" + mtrl_cate + "'";
//		}
//		List<Bis_bom> bisBomList = bisBomDao.find(hql);
//		List<String> mtrl_ids = new ArrayList<>();
//		if (bisBomList != null && bisBomList.size() >0){
//			for (Bis_bom bis_bom : bisBomList) {
//				mtrl_ids.add(bis_bom.getId().getMtrl_prod_id_fk());
//			}
//
//		}
//		String sql = "FROM Bis_bom where 1=1 ";
//		Set<String> arr = new HashSet<>();
//		ArrayList<FbpbisbomOA> oarys = new ArrayList<>();
//		List<Bis_bom> mtrl_ids1 = null;
//		if (mtrl_ids.size() > 0){
//			sql = sql + " and  id.mtrl_prod_id_fk in (:mtrl_ids)";
//			Query query = bisBomDao.getCrSession().createQuery(sql);
//			mtrl_ids1 = query.setParameterList("mtrl_ids", mtrl_ids).list();
//			if (mtrl_ids1.size() > 0) {
//				for (Bis_bom bis_bom : mtrl_ids1) {
//					arr.add(bis_bom.getId().getMdl_id_fk());
//				}
//				for (String s : arr) {
//					FbpbisbomOA oary = new FbpbisbomOA();
//					oary.setMdl_id_fk(s);
//					oarys.add(oary);
//				}
//				outTrx.setOary(oarys);
//				outTrx.setTbl_cnt(mtrl_ids1.size());
//			}
//		}



//		outTrx.setRtn_code(RETURN_CODE_OK);
//		outTrx.setRtn_mesg(RETURN_MESG_OK);
//	}

	public void errActionFnc(FbpbisbomO outTrx) {
		outTrx.setRtn_code("0000009");
		outTrx.setRtn_mesg("Invalid Action_flg");
	}

}
